<template>
	<view class="container">
		<view class="top-wrapper m-20-25-0">
			<template v-if="productType == 3 || productType == 4">
				<view class="address-wrapper" :class="{ 'border-top-divider': productType == 3 }"
					@click="selectShopAddress(1)">
					<view class="text">
						<view class="text" v-if="addressType == 'shop'">
							<view class="address">{{ addressText }}</view>
							<view class="name-tel">{{ userText }}</view>
						</view>
						<view class="address" v-else>{{ addressType == 'normal' ? '1-店内服务地址' : '1-选择“店内”地址' }}</view>
					</view>
					<image src="/static/next02.png" class="icon"></image>
				</view>
				<view class="address-wrapper he-auto" @click="selectAddress(2)">
					<view class="text">
						<view class="text" v-if="addressType == 'normal'">
							<view class="address">{{ addressText }}</view>
							<view class="name-tel">{{ userText }}</view>
						</view>
						<view class="address1" v-else>
							{{ addressType == 'shop' && loginType==2?'2-其他服务地址' :(productType == 3?'2-邮寄其他地址':'2-填写其他地址') }}
						</view>
					</view>
					<image src="/static/next02.png" class="icon"></image>
				</view>
				<view class="address-wrapper border-top" v-if="productType == 4">
					<view class="text jus" v-if="dateTime">
						<view class="address">上门时间</view>
						<view class="con">{{ dateTime }}</view>
					</view>
					<view class="text" v-else>
						<view class="address">请选择上门时间</view>
					</view>
					<image src="/static/next02.png" class="icon"></image>
					<uni-datetime-picker class="datetime-picker" v-model="dateTime" :border="false" :start="startTime"
						:hideSecond="true"></uni-datetime-picker>
				</view>
			</template>
			<view v-else class="address-wrapper he-auto" @click="selectAddress">
				<view class="text" v-if="addressList.length > 0">
					<view class="address">{{ addressText }}</view>
					<view class="name-tel">{{ userText }}</view>
				</view>
				<view class="text" v-else>
					<view class="address">请选择收货地址</view>
				</view>
				<image src="/static/next02.png" class="icon"></image>
			</view>
		</view>
		<view class="product-wrapper m-20-25-0" v-for="(shop, index) in orderDetails.shops" :key="shop.shopId">
			<view class="top-wrapper">
				<image src="/static/seller.png" class="icon"></image>
				<view class="name ell" style="color: red;">{{ shop.shopName }}</view>
			</view>
			<view class="list">
				<view :data-index="index" class="product-item" v-for="(product,index) in shop.products" :key="product.productId" 
					@touchstart="drawStart(shop.products,$event)" 
					@touchmove="drawMove(index,$event)"
					@touchend="drawEnd(index,$event)"
					:style="'right:'+product.right+'px'">
					<image :src="product.productImage" class="img" mode="aspectFill"></image>
					<view class="text">
						<view class="name ell">{{ product.productName }}</view>
						<view class="specifications ell" v-if="product.normal">{{ product.normal }}</view>
						<view class="num">x{{ product.num }}</view>
					</view>
					<view class="rightItem">
						<view class="price" style="color: red;" v-if="product.price==0">免费</view>
						<view class="price" v-else>￥{{ product.price }}</view>
					
						<view class="timeLimit" v-if="product.status==1">本产品已超出配送时段</view>
					</view>
					<view class="remove" @click="delFromCart(product)">删除</view>

					<!-- <view class="overlay lightbox" v-if="product.status==1"></view> -->
				</view>
				
			</view>
			<view class="total-amount border-top">小计 ¥{{ shop.shopTotalFee }}</view>
		</view>
		<view class="remark-wrapper m-20-25-0">
			<view class="title" style="color: red;">商家留言</view>
			<input type="text" v-model="remark" placeholder="对商家留言" />
		</view>
		<view class="payment-method-wrapper">
			<view class="title">选择支付方式</view>
			<view class="payment-method">
				<view class="payment-method-item" @click="selectPayMethod(1)">
					<image src="/static/balance.png" class="icon"></image>
					<view class="text">余额支付</view>
					<view class="checkbox-wrapper" :class="{ on: payMethod == 1 }">
						<image class="checkbox on" src="/static/checkbox_on.png"></image>
						<image class="checkbox off" src="/static/checkbox.png"></image>
					</view>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="payment-method-item wechat" @click="selectPayMethod(2)">
					<image src="/static/wechat.png" class="icon"></image>
					<view class="text">微信支付</view>
					<view class="checkbox-wrapper" :class="{ on: payMethod == 2 }">
						<image class="checkbox on" src="/static/checkbox_on.png"></image>
						<image class="checkbox off" src="/static/checkbox.png"></image>
					</view>
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-ALIPAY -->
				<view class="payment-method-item alipay" @click="selectPayMethod(3)">
					<image src="/static/alipay.png" class="icon"></image>
					<view class="text">支付宝支付</view>
					<view class="checkbox-wrapper" :class="{ on: payMethod == 3 }">
						<image class="checkbox on" src="/static/checkbox_on.png"></image>
						<image class="checkbox off" src="/static/checkbox.png"></image>
					</view>
				</view>
				<!-- #endif -->
			</view>
		</view>
		<view class="bottom-menu" :style="{ paddingBottom: tabbarBottom + 'px' }">
			<view class="total-amount">
				<text class="small">
					<text class="black">合计：</text>
					¥
				</text>
				{{ orderDetails.totalFee }}
			</view>
			<button type="default" :disabled="submitFlag || isHaveOutTimeProducts " class="btn" @click="createOrderConfirm">提交订单</button>
		</view>
		<view class="place"></view>
	</view>
</template>

<script>
	import {
		formatDate
	} from '@/utils/util.js';
	import {
		buyNowConfirmOrder,
		buyNowCreateOrder,
		carConfirmOrder,
		carCreateOrder,
		cartDeleteByProduct,
	} from '@/api/order.js';
	import {
		frontList
	} from '@/api/address.js';
	import uniDatetimePicker from '@/components/uni-datetime-picker/uni-datetime-picker.vue';
	import payment from '@/mixins/payment.js';
	export default {
		mixins: [payment],
		components: {
			uniDatetimePicker
		},
		data() {
			return {
				//列表数据（根据自己的业务获取）
				csListArrl:[],
				//左滑默认宽度
				delBtnWidth: 160,
				tabbarBottom: 0,
				submitFlag: false,
				isCheckedAddress: false,
				addressObj: {},
				addressList: [],
				addressType: '',
				startTime: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
				dateTime: '',
				buyType: '',
				productDetails: {},
				orderDetails: {},
				payMethod: 2,
				remark: '',
				carIds: '',
				productType: '',
				selectProvinceId: '',
				selectCityId: '',
				selectAreaId: '',
				address: '',
				loginType: 0,
				isHaveOutTimeProducts:false,
				ifAddressCanPut: 0,
				params:{},
			};
		},
		computed: {
			addressText() {
				if (this.addressObj) {
					return this.addressObj.provinceName + this.addressObj.cityName + this.addressObj.address;
				} else {
					return '请选择地址';
				}
			},
			userText() {
				if (this.addressObj) {
					return this.addressObj.name + '  ' + this.addressObj.mobile;
				} else {
					return '';
				}
			}
		},
		onShow() {
			const fixSize = () => {
				const {
					safeAreaInsets,
					platform
				} = uni.getSystemInfoSync();

				let barpx = 0;
				if (safeAreaInsets && safeAreaInsets.bottom) {
					if (safeAreaInsets.bottom > 0) {
						barpx = safeAreaInsets.bottom;
					} else {
						barpx = 0;
					}
				}
				if (platform == 'devtools') {
					this.tabbarBottom = barpx || 6;
				} else if (platform == 'ios') {
					this.tabbarBottom = barpx || 30;
				} else if (platform == 'android') {
					this.tabbarBottom = barpx || 30;
				}
			};

			fixSize();
		},
		onLoad(option) {
			this.loginType = option.loginType
			this.getOrderDetails(option);
		},
		methods: {
			// 地址列表
			getAddressList() {
				if (this.isCheckedAddress) {
					return;
				}
				frontList().then(respanse => {
					this.addressList = respanse.result;
					for (let i = 0; i < this.addressList.length; i++) {
						if (this.addressList[i].isDefault == 1) {
							this.addressObj = this.addressList[i];
							break;
						} else {
							this.addressObj = this.addressList[0];
						}
					}
				});
			},

			// 获取订单详情
			getOrderDetails(option) {
				//  buyType 1立即购买 2购物车
				this.buyType = option.buyType;
				if (this.buyType == 1) {
					this.productDetails = JSON.parse(decodeURIComponent(option.productDetails));
					console.log(this.productDetails);
					uni.setStorageSync('num', this.productDetails.productCount)
					this.getBuyNowConfirmOrder();
				} else {
					// 购物车
					this.carIds = option.cartIds;
					this.getCarConfirmOrder();
				}
			},

			// 立即购买获取订单
			getBuyNowConfirmOrder() {
				const {
					productCount,
					id
				} = this.productDetails;
				const data = {
					num: productCount,
					productId: id
				};
				buyNowConfirmOrder(data).then(res => {
					this.orderDetails = res.result;
					// 1.积分商品 2.特价商品 3.商户超市商品 4.商户服务 5.售货机商品
					this.beforeCreateOrder(res.result);
				});
			},

			// 购物车获取订单
			getCarConfirmOrder() {
				const data = {
					carIds: this.carIds
				};
				carConfirmOrder(data).then(res => {
					this.beforeCreateOrder(res.result);
				});
			},
			
			beforeCreateOrder(details){
				this.orderDetails = details;
				this.productType = this.orderDetails.shops[0].type;
				this.selectProvinceId = this.orderDetails.shops[0].provinceId;
				this.selectCityId = this.orderDetails.shops[0].cityId;
				this.selectAreaId = this.orderDetails.shops[0].districtId;
				this.address = this.orderDetails.shops[0].shopName;
				
				let this_ = this;
				this.orderDetails.shops.forEach(item=>{				
					item.products.forEach(product=>{
						if(product.status == 1){
							this_.isHaveOutTimeProducts = true;
						}
						
					})
					
				})
				if (this.productType != 3 && this.productType != 4) {
					this.getAddressList();
				}
				
				//判断有无不可以购买的商品
			},

			// 生成订单
			createOrderConfirm() {
				const {
					productCount,
					id,
					type
				} = this.productDetails;
				if (!this.addressObj.id) {
					uni.showToast({
						title: '请选择地址！',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				console.log({
					time: this.dateTime,
					type: this.productType
				});
				if (!this.dateTime && this.productType == 4) {
					uni.showToast({
						title: '请选择上门时间！',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (!this.payMethod) {
					uni.showToast({
						title: '请选择支付方式！',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				let content = '请确认本次订单为您服务的商家为'+this.orderDetails.shops[0].shopName;
				let this_ = this;
				uni.showModal({
						title: '提示',
						content: content,
						cancelText:'取消',
						confirmText: "确定",

						success: function(res) {
							if (res.confirm) {
								this_.createOrder();
							} else {
								// 执行取消后的操作
								uni.reLaunch({
									url: '/pages/store/map'
								})
							}
					}
				})
		
			},
			
			createOrder(){
				this.submitFlag = true;
				if (this.carIds) {
					//  购物车生成订单
					const data = {
						addressId: this.addressObj.id,
						carIds: this.carIds,
						payMethod: this.payMethod,
						memo: this.remark,
						addressType: this.ifAddressCanPut
					};
					carCreateOrder(data)
						.then(respanse => {
							this.handPayment(respanse.result)
						})
						.catch(err => {
							this.submitFlag = false;
						});
				} else {
					//  立即购买生成订单
					const data = {
						addressId: this.addressObj.id,
						num: this.productDetails.productCount,
						productId: this.productDetails.id,
						payMethod: this.payMethod,
						memo: this.remark,
						time: this.productType == 4 ? this.dateTime : null,
						addressType: this.ifAddressCanPut
					};
					buyNowCreateOrder(data)
						.then(respanse => {
							this.handPayment(respanse.result)
						})
						.catch(err => {
							this.submitFlag = false;
						});
				}
			},
			
			handPayment(detail,shopName){
				this.createOrderDetails = detail;
				
				//代表免费产品
				if(detail.totalFee==0 && detail.score==0){
					uni.redirectTo({
						url: `/pages/order/index?orderStatus=1`
					})
				}else{
					this.payment();	
				}
			
				
			},

			// 支付方式
			selectPayMethod(payMethod) {
				this.payMethod = payMethod;
			},
			registerAddressListener(type) {
				if (type == 'normal') {
					uni.$once('getAddress', address => {
						console.log({
							address
						});
						this.addressType = type;
						this.addressObj = address;
						this.addressList = [address];
					});
				} else {
					uni.$once('getAddress', address => {
						console.log({
							address
						});
						this.ifAddressCanPut = address.ifAddressCanPut;
						this.addressType = type;
						this.addressObj = address;
						this.addressList = [address];
					});
				}

			},
			selectShopAddress() {
				this.registerAddressListener('shop');
				let url = `/pages/address/shopAddress?selectProvinceId=${this.selectProvinceId}&selectCityId=${this.selectCityId}&selectAreaId=${this.selectAreaId}&address=${
                this.address
            }&loginType=${this.loginType}`;
				uni.navigateTo({
					url: url
				});
			},
			selectAddress() {
				this.registerAddressListener('normal');
				uni.navigateTo({
					url: '/pages/address/index'
				});
			},
			
			//开始触摸滑动
			drawStart(lists,e) {
				console.log("开始触发");
				var touch = e.touches[0];
				this.startX = touch.clientX;
				this.csListArrl = lists;
			},
			//触摸滑动
			drawMove(index,e) {
				console.log("滑动");
				
				this.$set(this.csListArrl[index],'right',0);
				
				var touch = e.touches[0];
				var item = this.csListArrl[e.currentTarget.dataset.index];
				var disX = this.startX - touch.clientX;
				if (disX >= 20) {
					if (disX > this.delBtnWidth) {
						disX = this.delBtnWidth;
					}
					this.$set(this.csListArrl[e.currentTarget.dataset.index],'right',disX);
				} else {
					this.$set(this.csListArrl[e.currentTarget.dataset.index],'right',0);
				}
			},
			//触摸滑动结束
			drawEnd(index,e) {
				console.log("滑动结束");
				var item = this.csListArrl[e.currentTarget.dataset.index];
				if (item.right >= this.delBtnWidth / 2) {
					this.$set(this.csListArrl[e.currentTarget.dataset.index],'right',this.delBtnWidth);
				} else {
					this.$set(this.csListArrl[e.currentTarget.dataset.index],'right',0);
				}
			},
			//从购物车中删除产品
			delFromCart(item){
				let this_ = this;
				uni.showModal({
						title: '提示',
						content: '确认删除该产品?',
						cancelText:'取消',
						confirmText: "确定",
				
						success: function(res) {
							if (res.confirm) {
								this_.deletePorductCart(item.productId);
							}
					}
				})
			},
			deletePorductCart(productId){
				cartDeleteByProduct(productId).then(res=>{
						if (this.buyType == 1) {
							uni.navigateBack();
						}else{
							this.isHaveOutTimeProducts = false;
							this.getCarConfirmOrder();
						}
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.jus {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-right: 20rpx;
	}

	.datetime-picker {
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		right: 0;
	}

	/deep/.uni-datetime-picker-text {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		height: 104rpx;
		opacity: 0;
	}

	.checkbox-wrapper {
		display: flex;
		align-items: center;

		.checkbox {
			width: 28rpx;
			height: 28rpx;

			&.on {
				display: none;
			}

			&.off {
				display: block;
			}
		}

		&.on {
			.checkbox.on {
				display: block;
			}

			.checkbox.off {
				display: none;
			}
		}
	}

	.m-20-25-0 {
		margin: 20rpx 25rpx 0;
		background: #ffffff;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.address-wrapper {
		position: relative;
		display: flex;
		align-items: center;
		min-height: 104rpx;
		box-sizing: border-box;
		padding: 34rpx 22rpx 25rpx 35rpx;
		background-color: #fff;

		&.he-auto {
			height: auto;
		}

		&::before {
			left: 25rpx;
			right: 22rpx;
		}

		&.border-top-divider {
			border-top: 0.5px solid #ededed;
		}

		.text {
			flex: 1;

			.con {
				font-size: 28rpx;
				color: #000000;
			}

			.address {
				line-height: 46rpx;
				font-size: 36rpx;
				font-weight: 600;
				color: #000000;
			}
			
			.address1{
				line-height: 46rpx;
				font-size: 32rpx;
				color: #333333;
			}

			.name-tel {
				margin-top: 16rpx;
				line-height: 34rpx;
				font-size: 24rpx;
				color: #666666;
			}
		}

		.icon {
			width: 14rpx;
			height: 24rpx;
		}
	}

	.product-wrapper {
		padding-top: 32rpx;

		.top-wrapper {
			display: flex;
			padding-left: 32rpx;

			.icon {
				margin: 2rpx 16rpx 0 0;
				width: 34rpx;
				height: 35rpx;
			}

			.name {
				flex: 1;
				overflow: hidden;
				line-height: 40rpx;
				font-size: 30rpx;
				font-weight: bold;
				color: #333333;
			}
		}

		.list {
			padding-top: 18rpx;
		
			
			

			.product-item {
				position: relative;
				display: flex;
				padding: 10rpx 23rpx 10rpx 32rpx;
				
				.remove {
					    width: 80px;
					    height: 100%;
					    background-color: red;
					    color: white;
					    position: absolute;
					    top: 0;
					    right: -165px;
					    display: flex;
					    justify-content: center;
					    align-items: center;
						font-size: 16px;
					}
		
				
				.overlay {
				  position: fixed;
				  top: 0;
				  right: 0;
				  bottom: 0;
				  left: 0;
				  background-color: black;
				
				  opacity: 0.1;
				
				}
				
				.lightbox { /*需要引起用户注意的元素*/
				  position: absolute;
				  z-index: 1;
				}

				.img {
					width: 156rpx;
					height: 156rpx;
					border-radius: 10rpx;
					background-color: #f5f5f5;
				}

				.text {
					flex: 1;
					padding-top: 7rpx;
					margin-left: 38rpx;
					overflow: hidden;

					.name {
						line-height: 38rpx;
						font-size: 28rpx;
						font-weight: bold;
						color: #080808;
					}

					.specifications {
						margin-top: 6rpx;
						line-height: 32rpx;
						font-size: 22rpx;
						color: #818181;
					}

					.num {
						margin-top: 19rpx;
						line-height: 38rpx;
						font-size: 28rpx;
						color: #818181;
					}
				}
				
				.rightItem{
					display: flex;
					flex-direction: column;
					line-height: 90rpx;
					align-items: right;
					.price {
						text-align: right;
						font-size: 30rpx;
						font-weight: bold;
						color: #080808;
					}
					.timeLimit{
						font-size: 30rpx;
						text-align: right;
						color: red;
					}
					
				}

				
				
			}
		}

		.total-amount {
			position: relative;
			padding-right: 23rpx;
		//	margin-top: 22rpx;
			line-height: 100rpx;
			text-align: right;
			font-size: 30rpx;
			font-weight: bold;
			color: #040404;
		}
	}

	.remark-wrapper {
		display: flex;
		padding-left: 24rpx;

		.title {
			line-height: 88rpx;
			font-size: 28rpx;
			color: #040404;
		}

		input {
			flex: 1;
			display: block;
			padding: 0 23rpx 0 20rpx;
			width: 100%;
			height: 88rpx;
			box-sizing: border-box;
			text-align: right;
			font-size: 28rpx;
			color: #040404;
		}
	}

	.payment-method-wrapper {
		margin: 0 25rpx 0;

		.title {
			line-height: 80rpx;
			font-size: 28rpx;
			color: #333333;
		}

		.payment-method {
			padding: 9rpx 0;
			background: #ffffff;
			border-radius: 10rpx;

			.payment-method-item {
				display: flex;
				align-items: center;
				padding: 24rpx 25rpx 24rpx 19rpx;

				.icon {
					width: 36rpx;
					height: 36rpx;
				}

				.text {
					flex: 1;
					margin-left: 19rpx;
					line-height: 36rpx;
					font-size: 28rpx;
					color: #333333;
				}
			}
		}
	}

	.bottom-menu {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 2;
		display: flex;
		padding: 12rpx 16rpx;
		background-color: #fff;

		.total-amount {
			flex: 1;
			margin-right: 37rpx;
			text-align: right;
			line-height: 80rpx;
			font-size: 46rpx;
			color: #eb6e37;

			.small {
				font-size: 26rpx;

				.black {
					color: #000000;
				}
			}
		}

		.btn {
			width: 220rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 28rpx;
			color: #fff;
			border-radius: 40rpx;
			background: linear-gradient(90deg, #eb7c3f, #ea5d2e);
		}
	}

	.place {
		height: 124rpx;
		visibility: hidden;
	}

	@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
		.bottom-menu {
			padding-bottom: calc(env(safe-area-inset-bottom)) !important;
			padding-bottom: calc(constant(safe-area-inset-bottom)) !important;
		}

		.place {
			padding-bottom: env(safe-area-inset-bottom) !important;
			padding-bottom: constant(safe-area-inset-bottom) !important;
		}
	}
</style>
